package whr.common.upload;

import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import whr.modules.assets.entity.InfoEntity;
import whr.modules.assets.service.InfoService;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("excel")
@Slf4j
public class ExcleExoprt {
    @Autowired
    private InfoService infoService;
    /**
     * 批量导出
     */
    @GetMapping("/export")
    public void export(@RequestParam(required = false) String assetsName, @RequestParam(required = false) String key2,
                       @RequestParam(required = false) String ids,
                       HttpServletResponse response) throws IOException {
        log.info("name{}",assetsName);  // 资产名
        log.info("key{}",key2);   // 状态
        ExcelWriter writer = ExcelUtil.getWriter(true);
        List<InfoEntity> list;
        QueryWrapper queryWrapper = new QueryWrapper<>();
        //导出勾选(条件加勾选)
        if(StringUtils.isNotBlank(ids)){
           /* String[] idsArr = ids.split(",");  //["1","2","3"]→ [1,2,3]*/
            String[] id = ids.split(",");
            Long[] idsArr= new Long[id.length];
            for (int i = 0; i <id.length ; i++) {
                idsArr[i]=Long.parseLong(id[i]);
            }
            queryWrapper.in("assets_id",idsArr);
        }else{
            // 第一种没有勾选默认全部导出(加条件)
            queryWrapper.like(StringUtils.isNotBlank(assetsName),"assets_name",assetsName);
            queryWrapper.eq(StringUtils.isNotBlank(key2),"assets_status",key2);
        }
        list = infoService.list(queryWrapper);
        writer.write(list,true);
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + URLEncoder.encode("信息表"+".xlsx", "UTF-8"));
        ServletOutputStream outputStream =response.getOutputStream();
        writer.flush(outputStream,true);
        outputStream.flush();
        outputStream.close();



    }


}
